package com.lzx.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.activity.entity.VoucherOrder;
import com.lzx.activity.mapper.VoucherOrderMapper;
import com.lzx.activity.service.VoucherOrderService;
import com.lzx.activity.service.VoucherService;
import com.lzx.activity.utils.RedisIdWorker;
import com.lzx.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lzx
 * @since 2022-11-10
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements VoucherOrderService {
    @Resource
    private VoucherOrderMapper voucherOrderMapper;

    @Resource
//    @Lazy //解决循环依赖
    private VoucherService voucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("secKill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //优惠券秒杀（需先将优惠价添加到redis中）
    @Override
    public R voucherSecKill(Long id, Long userId) {
        long orderId = redisIdWorker.nextId("order");
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                id.toString(), userId.toString(), String.valueOf(orderId)
        );
        assert result != null;
        int r = result.intValue();
        //2.判断结果是否为0
        if (r != 0) {
            //2.1.不为0 ，代表没有购买资格
            return R.error().message(r == 1 ? "库存不足" : "不能重复下单");
        }
        //2.2.为0 ，有购买资格，把下单信息保存到阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        //2.3.订单id
        voucherOrder.setId(orderId);
        //2.4.用户id
        voucherOrder.setUserId(Math.toIntExact(userId));
        //2.5.优惠券id
        voucherOrder.setVoucherId(Math.toIntExact(id));
        //3.一人一啖
        //3.1查询订单
        int count = Math.toIntExact(query().eq("user_id", userId).eq("voucher_id", voucherOrder.getVoucherId()).count());
        //3.2判断是否存在
        if (count > 0) {
            //用户已经购买过了
            log.error("用户已经购买过一次!");
            return R.error().message("用户已经购买过一次!");
        }
        //使用MQ来发送消息，MQ监听到消息并保存订单和扣减库存
        rocketMQTemplate.convertAndSend("secKill-topic", voucherOrder);
        //6.返回订单id
        return R.ok().message(String.valueOf(orderId));
    }

    //MQ服务保存订单和扣减库存
    @Transactional
    @Override
    public String saveOrderAndReduceStock(VoucherOrder voucherOrder) {
        //4.扣减库存
        boolean success = voucherService.update()
                .setSql("stock = stock -1")
                .eq("id", voucherOrder.getVoucherId()).gt("stock", 0)    //CAS解决超卖问题
                .update();
        if (!success) {
            log.error("库存不足");
            return "库存不足";
        }
        //5.创建订单
        voucherOrderMapper.insert(voucherOrder);
        return null;
    }

    //根据优惠券d获取抢购详情
    @Override
    public R getVoucherOrderById(Integer voucherId, int current, int size) {
        QueryWrapper<VoucherOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("voucher_id", voucherId);
        Page<VoucherOrder> page = new Page<>(current, size);
        voucherOrderMapper.selectPage(page, wrapper);
        Map<String, Object> map = new HashMap<>();
        List<VoucherOrder> list = page.getRecords();//当前页数据
        long total = page.getTotal();//总记录数
        map.put("list", list);
        map.put("total", total);
        return R.ok().data("map", map);
    }

    //优惠券秒杀
//    @Override
//    public R voucherSecKill(Long id, Long userId) {
//        //1.查询优惠券
//        Voucher voucher = voucherMapper.selectById(id);
//        //2.判断秒杀是否开始
//        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return R.error().message("秒杀尚未开始!");
//        }
//        //3.判断秒杀是否已经结束
//        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return R.error().message("秒杀已经结束!");
//        }
//        //4.判断库存是否充足
//        if (voucher.getStock() < 1) {
//            return R.error().message("库存不足");
//        }
//
//        //悲观锁
////        synchronized (userId.toString().intern()) {
////            //获取代理对象（事务）    解决事务不生效的问题
////            VoucherOrderService proxy = (VoucherOrderService) AopContext.currentProxy();
////            return proxy.createVoucherOrder(id, userId);
////        }
//        // 创建锁对象
//        //自定义锁
////        SimpleRedisLock redisLock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
//        //Redisson锁
//        RLock redisLock = redissonClient.getLock("lock:order:" + userId);
//        // 尝试获取锁
//        boolean isLock = redisLock.tryLock();
//        // 判断
//        if (!isLock) {
//            // 获取锁失败，直接返回失败或者重试
//            return R.error().message("不允许重复下单!");
//        }
//        try {
//            //获取代理对象（事务）    解决事务不生效的问题
//            VoucherOrderService proxy = (VoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(id, userId);
//        } finally {
//            // 释放锁
//            redisLock.unlock();
//        }
//    }
}
